package org.lonetree.tc.webapp.actions;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.Book;
import org.lonetree.tc.core.BookComment;
import org.lonetree.tc.core.User;
import org.lonetree.tc.core.Book.Isbn;
import org.lonetree.tc.core.BookComment.BookCommentId;
import org.lonetree.tc.core.User.Username;
import org.lonetree.tc.core.dao.BookDAO;
import org.lonetree.tc.core.dao.DAOFactory;
import org.lonetree.tc.webapp.forms.BookCommentForm;


public class AddBookComment extends SecureAction {

	@Override
	public ActionForward executeSecure(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		try{
			DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.FactoryImplementation.DB_DAO_FACTORY);
			BookDAO bdao = factory.getBookDAO();
			if (request.getMethod().toLowerCase().equals("get"))
			{
				String isbn=request.getParameter("isbn");
				Book book=bdao.getBook(new Isbn(isbn));
				request.setAttribute("loaded", book);
				return mapping.findForward("success_get");
			}
			
			if (request.getMethod().toLowerCase().equals("post"))
			{
				Book parentBook=bdao.getBook(new Isbn(request.getParameter("isbn")));
				String addedComment=request.getParameter("newcomment");
				BookComment newComment=new BookComment(parentBook,getCurrentUser(),
						addedComment,false); 
				User u=getCurrentUser();
				
				parentBook.getComments().add(newComment);
				bdao.updateBook(parentBook);
				request.setAttribute("isbn", request.getParameter("isbn"));
				return mapping.findForward("success_post");
			}
			
			return mapping.findForward("failure");
		}
		catch (Exception e)
		{
			return mapping.findForward("failure");
		}
	}

}
